package tool

import (
	_ "bytes"
	"encoding/json"
	_ "fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"strings"
	"time"
)

type S struct {
	Param  []Params `json:"param"`
	Header []Params `json:"header_param"`
}

type Params struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

/**
func doPost(request_url string, param *S) (string, error) {
	var client = &http.Client{}
	postValues := url.Values{}
	for _, v := range param.Param {
		postValues.Add(v.Key, v.Value)
	}

	resp, err := client.PostForm(request_url, postValues)

	if err != nil {
		fmt.Println(err.Error())
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(body))
	return string(body), err
}**/

/**
*复杂的请求
**/
func HttpRequest(request_url string, types string, param *S) (string, string, error) {

	client := &http.Client{
		Transport: &http.Transport{ //设置超时时间
			Dial: func(netw, addr string) (net.Conn, error) {
				deadline := time.Now().Add(25 * time.Second)
				c, err := net.DialTimeout(netw, addr, time.Second*20)
				if err != nil {
					return nil, err
				}
				c.SetDeadline(deadline)
				return c, nil
			},
		},
	}
	b := strings.NewReader("")
	if len(param.Param) > 0 {
		//设置参数
		form := url.Values{}
		for _, v := range param.Param {
			form.Set(v.Key, v.Value)
		}
		b = strings.NewReader(form.Encode())
	}

	req, err := http.NewRequest(types, request_url, b)

	if err != nil {
		return "", "", err
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	//组装请求头
	if len(param.Header) > 0 {
		for _, v := range param.Header {
			req.Header.Set(v.Key, v.Value)
		}
	}

	resp, err := client.Do(req)

	defer resp.Body.Close() //最后都会执行

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", "", err
	}

	headerstr, err := json.Marshal(resp.Header)
	//响应输出
	return string(body), string(headerstr), err
}
